package meta

import (
	"context"
	apiv1 "gomod.alauda.cn/mysql-mgr-operator/api/v1"
	"k8s.io/apimachinery/pkg/types"
	"satellite/app/option"
	"satellite/pkg/mgrclient"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

type BaseOption struct {
	option.Base
}

type Base struct {
	*BaseOption
}

func NewBase(opt *BaseOption) *Base {
	return &Base{BaseOption: opt}
}

func (b *Base) metaName() string {
	return b.Name + "-meta"
}

func (b *Base) getMeta() (*apiv1.MySQLMeta, error) {
	ctx, cancel := context.WithTimeout(context.Background(), b.Timeout)
	defer cancel()
	nn := types.NamespacedName{
		Namespace: b.Namespace,
		Name:      b.metaName(),
	}
	metaCr := new(apiv1.MySQLMeta)
	err := mgrclient.Client().Get(ctx, nn, metaCr)
	if err != nil {
		return nil, err
	}
	return metaCr, nil
}

func (b *Base) update(obj client.Object) error {
	ctx, cancel := context.WithTimeout(context.Background(), b.Timeout)
	defer cancel()
	return mgrclient.Client().Update(ctx, obj)
}

func (b *Base) updateStatus(obj client.Object) error {
	ctx, cancel := context.WithTimeout(context.Background(), b.Timeout)
	defer cancel()
	return mgrclient.Client().Status().Update(ctx, obj)
}
